package com.time.workbench.oss.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.*;
import com.time.workbench.oss.config.OssConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.UUID;

@Service
public class FileService {
    @Autowired
    private OSS ossClient;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public String uploadOss(File file) {
        String dateStr = DateUtil.format(new Date(), "yyyyMMdd");

        String fileUrl = OssConfig.objectName + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") ) + "." + FileNameUtil.extName(file);

        PutObjectRequest putObjectRequest = new PutObjectRequest(OssConfig.bucketName, fileUrl, file);

        ObjectMetadata metadata = new ObjectMetadata();
        putObjectRequest.setMetadata(metadata);
        ossClient.putObject(putObjectRequest);
        return OssConfig.bucketUrl + "/" + fileUrl;
    }
}
